package com.dld.coupon.activity;

import java.util.List;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;

import com.constant.net.Constant;
import com.dld.android.persistent.SharePersistent;
import com.dld.android.util.LogUtils;
import com.dld.coupon.util.MapUtil;
import com.dld.coupon.util.StringUtils;
import com.dld.coupon.util.UserConfig;
import com.dld.coupon.view.CouponDownLoadAdapter;
import com.dld.coupon.view.DownloadListView;
import com.dld.protocol.ProtocolHelper;
import com.dld.protocol.json.AroundResponse;
import com.dld.protocol.json.Coupon;
import com.dld.protocol.json.CouponDetail;
import com.dld.protocol.json.PageInfo;
import com.dld.protocol.json.Protocol;
import com.tencent.weibo.utils.Cache;

public class AroundActivity extends ListTabActivity {
	private static final int FIRST_PAGE_INDEX = 1;
	private static final int PAGE_SIZE = 10;
	private static String cityId;
	private static String cityName;
	public static MapUtil.LatAndLon location;
	static final String[] sortLabel;
	static final String[] sortString;
	static final int[] sortTypes;
	private Coupon coupon = new Coupon();
	private DownloadListView.DownLoadAdapter couponAdapter;
	private DownloadListView couponListView;

	private Handler testposthandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 0xff) {
				List<CouponDetail> list_around = (List<CouponDetail>) msg.obj;
				
				Log.v("","********************  data size  "+list_around.size());

				Log.v("", "show data for the  listview  ************  "
						+ msg.arg2);
				if (Constant.AROUND_TYPE_COUPON == AroundActivity.this.type) {
					if (msg.arg2 == Constant.LISTVIEW_RESET) {
						AroundActivity.this.coupon.details.clear();
					}
					AroundActivity.this.coupon.details.addAll(list_around);
					AroundActivity.this.coupon.pageInfo = new PageInfo();
					AroundActivity.this.coupon.pageInfo.total = msg.arg1;
					if (msg.arg1 > 0) {
						AroundActivity.this.couponAdapter.notifyDownloadBack();
					} else {
						AroundActivity.this.couponAdapter.notifyNoResult();
					}
					couponListView.setVisibility(View.VISIBLE);
					storeListView.setVisibility(View.GONE);

				}
				if (Constant.AROUND_TYPE_STORE == AroundActivity.this.type) {
					if (msg.arg2 == Constant.LISTVIEW_RESET) {
						AroundActivity.this.store.details.clear();
					}
					AroundActivity.this.store.details.addAll(list_around);
					AroundActivity.this.store.pageInfo = new PageInfo();
					AroundActivity.this.store.pageInfo.total = msg.arg1;
					if (msg.arg1 > 0) {
						AroundActivity.this.storeAdapter.notifyDownloadBack();
					} else {
						AroundActivity.this.storeAdapter.notifyNoResult();
					}
					couponListView.setVisibility(View.GONE);
					storeListView.setVisibility(View.VISIBLE);
				}

			} else if (msg.what == 0) {
				showFailedView();
			}
		}
	};

	private Handler handler = new Handler() {
		private void showCoupon(boolean paramBoolean, Coupon paramCoupon,
				DownloadListView paramDownloadListView, Message paramMessage,
				int flag) {
			if ((AroundActivity.this.locationFailedFlag)
					|| (AroundActivity.location != null)) {
				if ((AroundActivity.location != null)
						|| (AroundActivity.this.locationFailedFlag)) {
					int view_type = paramBoolean ? 1 : 2;
					Protocol localProtocol = ProtocolHelper.buildAroundSearch(
							AroundActivity.this,
							AroundActivity.this.category.code,
							Constant.INVALID_VLAUE, view_type, 10,
							paramMessage.arg1);
					AroundActivity.this.lastUrl = localProtocol
							.getAbsoluteUrl();

					AroundResponse ar = new AroundResponse(String.class,
							testposthandler, paramDownloadListView, flag);
					localProtocol.startTrans(ar);

				}

			}
		}

		@Override
		public void handleMessage(Message paramMessage) {

			LogUtils.log("test", "around,    msg: " + paramMessage.what);

			if ((!AroundActivity.this.locationFailedFlag)
					&& (AroundActivity.location == null))
				return;

			if (paramMessage.what == 1) {
				AroundActivity.this.couponAdapter.notifyDownloadBack();
			}

			if (paramMessage.what == 3) {
				Object localObject = (TextView) AroundActivity.this
						.findViewById(R.id.location);
				if ((AroundActivity.location == null) && (localObject != null))
					((TextView) localObject).setText("十分抱歉，未能定位您所在的位置。");
				if (AroundActivity.this.type == 5) {
					showCoupon(true, AroundActivity.this.store,
							AroundActivity.this.storeListView, paramMessage,
							Constant.LISTVIEW_RESET);
				} else {
					AroundActivity.this.showFailedView();
				}
			} else if (paramMessage.what == 4) {
				AroundActivity.this.showFailedView();
			} else if (paramMessage.what == Constant.AROUND_TYPE_STORE) {
				showCoupon(true, AroundActivity.this.store,
						AroundActivity.this.storeListView, paramMessage,
						Constant.LISTVIEW_ADD);
			} else if (paramMessage.what == Constant.AROUND_TYPE_COUPON) {
				showCoupon(false, AroundActivity.this.coupon,
						AroundActivity.this.couponListView, paramMessage,
						Constant.LISTVIEW_ADD);
			} else if (paramMessage.what == Constant.AROUND_RESET) {
				if (paramMessage.arg1 == Constant.AROUND_TYPE_COUPON) {
					paramMessage.arg1 = 1;// request page index
					showCoupon(false, AroundActivity.this.coupon,
							AroundActivity.this.couponListView, paramMessage,
							Constant.LISTVIEW_RESET);
				} else {
					paramMessage.arg1 = 1;// request page index
					showCoupon(true, AroundActivity.this.store,
							AroundActivity.this.storeListView, paramMessage,
							Constant.LISTVIEW_RESET);
				}
			}

			if (paramMessage.arg2 > 0) {
				Cache.remove(AroundActivity.this.lastUrl);
			}

		}
	};

	private MapUtil.LatAndLon lastLocation;
	private String lastUrl = "";
	private boolean locationFailedFlag = false;
	private View locationSuccess;
	private boolean locationing;
	private View mNoResultView;
	private View notAllowGps;
	private MapUtil.LocationObserver ob = new MapUtil.LocationObserver() {
		public void onFailed() {
			if (AroundActivity.location == null)
				AroundActivity.this.locationFailedFlag = true;
			AroundActivity.this.handler.sendEmptyMessage(3);
		}

		public void onLocationChanged(MapUtil.LatAndLon paramLatAndLon) {
			try {
				LogUtils.log("test", "locationUpdated");
				if (paramLatAndLon != null) {
					MapUtil.LatAndLon localLatAndLon = AroundActivity.location;
					if ((localLatAndLon == null)
							|| (Math.abs(localLatAndLon.lat
									- paramLatAndLon.lat) >= 0.001D)
							|| (Math.abs(localLatAndLon.lon
									- paramLatAndLon.lon) >= 0.001D)) {
						AroundActivity.location = paramLatAndLon;
						AroundActivity.this.locationing = false;
						AroundActivity.this.locationFailedFlag = false;
						if (AroundActivity.this.getListSize() == 0)
							AroundActivity.this.request(
									AroundActivity.this.type, 1);
					}
				}
			} catch (Exception localException) {
				LogUtils.e("test", "", localException);
			}
		}

		public void onCityChanged(String currentCity) {

		}
	};
	private boolean showingDialog = false;
	private int sortIndex;
	private Coupon store = new Coupon();
	private DownloadListView.DownLoadAdapter storeAdapter;
	private DownloadListView storeListView;
	private int type;

	static {
		sortTypes = new int[] { 2, 1 };
		sortString = new String[] { "默认排序", "按距离排序" };
		sortLabel = new String[] { "默认↓", "距离↓" };
	}

	private boolean checkNetwork() {
		boolean bool = false;
		Object localObject = (ConnectivityManager) getSystemService("connectivity");
		if (((ConnectivityManager) localObject).getActiveNetworkInfo() != null)
			bool = ((ConnectivityManager) localObject).getActiveNetworkInfo()
					.isAvailable();
		if ((!bool) && (!this.showingDialog)) {
			this.showingDialog = true;
			localObject = new AlertDialog.Builder(this).setTitle("没有可用的网络")
					.setMessage("网络访问失败，请检查网络连接。");
			((AlertDialog.Builder) localObject).setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(
								DialogInterface paramDialogInterface,
								int paramInt) {
							Intent localIntent = new Intent("/");
							localIntent.setComponent(new ComponentName(
									"com.android.settings",
									"com.android.settings.WirelessSettings"));
							localIntent.setAction("android.intent.action.VIEW");
							AroundActivity.this.startActivity(localIntent);
							AroundActivity.this.showingDialog = false;
						}
					}).setNeutralButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(
								DialogInterface paramDialogInterface,
								int paramInt) {
							paramDialogInterface.cancel();
							AroundActivity.this.showingDialog = false;
						}
					}).create();
			((AlertDialog.Builder) localObject).show();
		}
		return bool;
	}

	private void doShowList(int msg_what, DownloadListView paramDownloadListView) {
		this.storeListView.setVisibility(View.GONE);
		this.couponListView.setVisibility(View.GONE);
		paramDownloadListView.setVisibility(View.VISIBLE);

		showSuccessView();
		request(msg_what, 1);
	}

	private int getListSize() {
		int i;
		switch (this.type) {
		case 5:
			i = this.coupon.details.size();
			break;
		case 25:
			i = this.store.details.size();
			break;
		default:
			i = this.coupon.details.size();
		}
		return i;
	}

	private void initCouponListview() {
		this.couponListView = ((DownloadListView) findViewById(R.id.couponlistview));
		this.couponAdapter = new ListViewAdapter(false, this.coupon,
				couponListView, Constant.VIEW_COUPON);
		this.couponListView.setAdapter(this.couponAdapter);
		initListView(this.couponListView, this.coupon, false);
	}

	private void initDistanceSpinner() {
//		final TextView localTextView = (TextView) findViewById(R.id.distance_spinner);
//		localTextView.setOnClickListener(new OnClickListener() {
//			public void onClick(View v) {
//				if (AroundActivity.this.type == Constant.AROUND_TYPE_COUPON) {
//					AroundActivity.this.coupon.details.clear();
//					AroundActivity.this.couponAdapter.notifyDownload();
//				} else {
//					AroundActivity.this.store.details.clear();
//					AroundActivity.this.storeAdapter.notifyDownload();
//				}
//				request_category();
//			}
//		});
		// localTextView.setOnClickListener(new View.OnClickListener() {
		// public void onClick(View paramView) {
		//
		// DialogInterface.OnClickListener local1 = new
		// DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface paramDialogInterface,
		// int paramInt) {
		// paramDialogInterface.dismiss();
		// if (AroundActivity.this.sortIndex != paramInt) {
		// AroundActivity.this.sortIndex = paramInt;
		// localTextView
		// .setText(AroundActivity.sortLabel[paramInt]);
		//
		// Message m = Message.obtain();
		// m.what = Constant.AROUND_RESET;
		// m.arg1 = AroundActivity.this.type;
		// AroundActivity.this.handler.sendMessage(m);
		// }
		// }
		// };
		// new AlertDialog.Builder(AroundActivity.this)
		// .setTitle("请选择排序方式").setSingleChoiceItems(
		// AroundActivity.sortString,
		// AroundActivity.this.sortIndex, local1).show();
		//
		// }
		// });
	}

	private void initListView(final DownloadListView paramDownloadListView,
			final Coupon paramCoupon, final boolean paramBoolean) {
		paramDownloadListView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView<?> paramAdapterView,
							View paramView, int paramInt, long paramLong) {

						CouponDetail ainfo = (CouponDetail) paramView.getTag();

						Cache.put("coupon", paramCoupon);

						CouponDetail cdd = (CouponDetail) paramView.getTag();
						Log.v("", "*******************   store detail view"
								+ cdd.getDisid());
						if (paramDownloadListView == AroundActivity.this.couponListView) {
							Intent it = new Intent(paramView.getContext(),
									MyCouponDetail.class);
							it
									.putExtra(Constant.CONSTANT_DISID, cdd
											.getDisid());
							it.putExtra("previous_pos",
									BaseActivity.segmentPosition);
							paramView.getContext().startActivity(it);
						} else {
							Intent it = new Intent(paramView.getContext(),
									StoreDetail.class);
							it.putExtra(Constant.CONSTANT_SHOPID, ""
									+ cdd.getShopid());
							it.putExtra("previous_pos",
									BaseActivity.segmentPosition);
							paramView.getContext().startActivity(it);
						}
					}
				});
	}

	private void initLocation() {
		this.notAllowGps = findViewById(R.id.no_location_view);
		((Button) this.notAllowGps.findViewById(R.id.setting_gps_button))
				.setOnClickListener(new View.OnClickListener() {
					public void onClick(View paramView) {
						UserConfig.setAllowLocationService(AroundActivity.this,
								true);
						AroundActivity.this.showSuccessView();
						AroundActivity.this.requestLocation();
					}
				});
	}

	private void initRefresh() {
		View refresh = findViewById(R.id.refresh);
		refresh.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Log.v("", "***************  refresh  the view list ");
				if (AroundActivity.this.type == Constant.AROUND_TYPE_COUPON) {
					AroundActivity.this.coupon.details.clear();
					AroundActivity.this.couponAdapter.notifyDownload();
				} else {
					AroundActivity.this.store.details.clear();
					AroundActivity.this.storeAdapter.notifyDownload();
				}
				request_category();
			}
		});

	}

	private void initStoreListview() {
		this.storeListView = ((DownloadListView) findViewById(R.id.storelistview));
		this.storeAdapter = new ListViewAdapter(true, this.store,
				storeListView, Constant.VIEW_AROUND_STORE);
		this.storeListView.setAdapter(this.storeAdapter);
		initListView(this.storeListView, this.store, true);
	}

	private void initTypeSpinner() {
		final TextView localTextView = (TextView) findViewById(R.id.type_spinner);
		localTextView.setOnClickListener(new View.OnClickListener() {
			public void onClick(View paramView) {
				DialogInterface.OnClickListener local1 = new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface paramDialogInterface,
							int paramInt) {

						paramDialogInterface.dismiss();
						switch (paramInt) {
						case 0:
							if (type == Constant.AROUND_TYPE_COUPON)
								return;
							type = Constant.AROUND_TYPE_COUPON;
							AroundActivity.this.showCoupon();
							localTextView.setText(R.string.coupon);
							break;
						case 1:
							if (type == Constant.AROUND_TYPE_STORE)
								return;
							type = Constant.AROUND_TYPE_STORE;
							AroundActivity.this.showStore();
							localTextView.setText(R.string.group1);
							break;
						}
					}
				};
				new AlertDialog.Builder(AroundActivity.this)
						.setTitle("请选择搜索类型").setSingleChoiceItems(
								R.array.types,
								AroundActivity.this.type == 5 ? 0 : 1, local1)
						.show();

			}
		});
	}

	private void refresh() {
		new Thread() {
			public void run() {
				if (Cache.getCache("gps_address") == null) {
					if (MapUtil.isInited())
						MapUtil.reverseGeoCode(null, AroundActivity.this,
								AroundActivity.this.ob);
				} else
					MapUtil.updateAddress(AroundActivity.this,
							AroundActivity.this.handler);
			}
		}.start();
	}

	private void request(int msg_what, int curPageIndex) {
		request(msg_what, curPageIndex, false);
	}

	private void request(int msg_what, int curPageIndex, boolean paramBoolean) {

		if ((location != null) || (this.locationFailedFlag)) {
			int i = paramBoolean ? 0 : 1;
			Message m = Message.obtain();
			m.what = msg_what;
			m.arg1 = curPageIndex;
			m.arg2 = i; // is store or copon
			this.handler.sendMessage(m);
		} else {
			// this.couponAdapter.notifyException();
			// this.storeAdapter.notifyException();
		}
	}

	private void requestLocation() {
		LogUtils.log("main", "start_time" + System.currentTimeMillis());
		if (location != null) {
			request(this.type, 1);
		} else {
			this.locationing = true;
			MapUtil.regist(this.ob, this.handler, this);
		}
	}

	private void showCoupon() {
		showList(Constant.AROUND_TYPE_COUPON, this.couponListView);

	}

	private void showFailedView() {
		this.locationSuccess.setVisibility(8);
		this.notAllowGps.setVisibility(8);
		this.mNoResultView.setVisibility(0);
	}

	private void showList(int msg_what, DownloadListView paramDownloadListView) {
		if (!this.locationFailedFlag)
			doShowList(msg_what, paramDownloadListView);
		else
			this.handler.sendEmptyMessage(3);
	}

	private void showSuccessView() {
		if (this.locationSuccess.getVisibility() != View.VISIBLE)
			this.locationSuccess.setVisibility(View.VISIBLE);
		if (this.notAllowGps.getVisibility() != View.GONE)
			this.notAllowGps.setVisibility(View.GONE);
		if (this.mNoResultView.getVisibility() != View.GONE)
			this.mNoResultView.setVisibility(View.GONE);
	}

	public void init() {
		this.type = Constant.AROUND_TYPE_COUPON;
		this.sortIndex = 0;
		this.locationFailedFlag = false;
		if (StringUtils.isEmpty(cityId))
			cityId = SharePersistent.getInstance().getPerference(this,
					"city_id");
		if (StringUtils.isEmpty(cityName))
			cityName = SharePersistent.getInstance().getPerference(this,
					"city_name");
		this.mNoResultView = findViewById(R.id.no_result_view);
		this.locationSuccess = findViewById(R.id.location_success_view);

		initDistanceSpinner();
		initTypeSpinner();
		initCategoryList();
		initRefresh();
		initStoreListview();
		initCouponListview();
		initLocation();
		showCoupon();
	}

	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.around_view);
		init();
		if (checkNetwork()) {
			showSuccessView();
			if (location == null)
				requestLocation();
		} else {
			showFailedView();
		}
		showCoupon();

		new Thread() {
			public void run() {
				if (Cache.getCache("gps_address") != null)
					MapUtil.updateAddress(AroundActivity.this,
							AroundActivity.this.handler);
				if ((AroundActivity.location != null)
						|| (AroundActivity.this.locationing)) {
					if (Cache.getCache("gps_address") == null) {
						if (MapUtil.isInited())
							MapUtil.reverseGeoCode(null, AroundActivity.this,
									AroundActivity.this.ob);
					} else
						MapUtil.updateAddress(AroundActivity.this,
								AroundActivity.this.handler);
				} else
					AroundActivity.this.requestLocation();
			}
		}.start();
		CityActivity.registObserver(this);
	}

	protected void onResume() {
		super.onResume();

	}

	protected void request() {
		request(this.type, 1);
	}

	public void showStore() {
		showList(Constant.AROUND_TYPE_STORE, this.storeListView);
	}

	protected class ListViewAdapter extends CouponDownLoadAdapter {
		public ListViewAdapter(boolean isStore, Coupon c,
				DownloadListView dlist, int viewtype) {
			super(isStore, dlist, c, viewtype);
		}

		public Context getContext() {
			return AroundActivity.this;
		}

		public void onNotifyDownload() {
			AroundActivity localAroundActivity = AroundActivity.this;
			int i = !this.isStore ? Constant.AROUND_TYPE_COUPON
					: Constant.AROUND_TYPE_STORE;
			localAroundActivity.request(i, 1 + getListCount() / 10);
		}
	}

	@Override
	protected void request_category() {
		Message m = Message.obtain();
		m.what = Constant.AROUND_RESET;
		m.arg1 = AroundActivity.this.type;
		AroundActivity.this.handler.sendMessage(m);
	}
}
